<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/7/3
 * Time: 10:27
 */
namespace app\admin\controller;
use think\Controller;
use think\Session;
use think\Db;
use think\Request;
use think\Loader;
use think\Config;
use app\admin\model\Index as IndexModel;
use app\admin\model\Site as SiteModel;
use app\admin\model\ModelM as ModelMModel;
class Common extends Controller
{
	protected $config=array();
	protected $tpl_dir=array();
    public function _initialize()
    {
		$this->config=cache_config();
		$this->checkLogin();
		// 不进行表单检验的控制器
		 // POST表单提交校验
       /* if ($this->request->isPost() && session('formcheck') != input('formcheck')) {

            alert('表单提交校验失败,请刷新后重试！','back');
        }*/
		 // 首次加载时，生成页面验证码
        if (!Session::has('formcheck')) {
            session('formcheck', get_uniqid());
        }
        $this->assign('formcheck', session('formcheck'));
		$this->assign('contraction', $this->request->controller());
		$this->assign('thisurl', $this->request->url());
		$this->tpl_dir=config('tpl_dir');
		//获取模型名称
		$Modeldel=new ModelMModel();
		$mcode=input('mcode');
        $this->assign('model_name', $Modeldel->getName($mcode));
		$this->assign('mcode', $mcode);

		$Modelsite=new SiteModel();

		$sitename=$Modelsite->getsitename();
		$this->assign('sitename', $sitename);
		
		$lanmulist=$Modeldel->getModelMenu();
		$this->assign('lanmulist', $lanmulist);

		
    }
	// 后台用户登录状态检查
    private function checkLogin()
    {
        if (session('sid') && $this->checkSid()) { // 如果已经登录直接true
			$Model = new IndexModel();
			$this->assign('user_info', $Model->getUserInfo(session('ucode')));
            return true;
        }else { // 未登录跳转到登录页面
            location(url('Login/index'));
        }
    }

    // 检查会话id
    private function checkSid()
    {
        $sid = encrypt_string(session_id() . session('id'));
        if ($sid != session('sid')) {
            session_destroy();
            return false;
        } else {
            return true;
        }
    }

    //调用栏目列表数据
    private function CallRuleList($pcode='0',$BackData=array())
    {
        $Where=[];
        $Where['pcode']=$pcode;
        //$Where['ishow']='1';
        $Where['status']='1';
        $List=Db::name('content_sort')->field('id,name,mcode,scode,pcode,status')->where($Where)->order('sorting asc,id asc')->select();
        if(empty($List))
        {
            return $BackData;
        }else{
            foreach ($List as $key=>$val)
            {
                $BackData[]=$val;
                $BackData=$this->CallRuleList($val['id'],$BackData);
            }
            return $BackData;
        }
    }
    //获取栏目
    private function GetMenu($List)
    {
        if(empty($List)){ return false;}
        $Back=[];$Data=[];$Seat=0;$OneMenuLink=[];$DefaultOneID=0;
        foreach ($List as $key=>$val)
        {
            if($val['node']=='1')
            {
                $Seat=1;//获取三级连接时当前要循环的位置
                $Data['One'][$val['id']]=$val;//获取所有的一级栏目的具体数据
                if($key==0)
                {
                    $DefaultOneID=$val['id'];
                }
            }
            if($val['node']=='2')
            {
                $Data['Two'][$val['parentid']][$val['id']]=$val;//获取所有二级栏目的具体数据，并和一级栏目进行绑定
            }
            if($val['node']=='3')
            {
                $PathArr=explode(',',$val['path']);//基于路径拆分出一级栏目的ID
                if($Seat==1)//验证当前三级分类的位置是否是第一个
                {
                    $OneMenuLink[$PathArr[0]]='/'.$val['name'];//获取第一个一级栏目所对应的连接
                }
                $Data['Three'][$PathArr[0]][$PathArr[1]][$val['id']]=$val;//获取所有一级栏目的具体数据，并和一级栏目进行绑定
                $Seat++;
            }
        }
        $Back['Data']=$Data;
        $Back['OneMenuLink']=$OneMenuLink;
        $Back['DefaultOneID']=$DefaultOneID;
        return $Back;
    }
    //单文件上传
    protected function OneUpload($FileName=''){
        if(empty($FileName)) return false;
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file($FileName);
        if(empty($file)){ return false;}
        // 移动到框架应用根目录/public/uploads/ 目录下
        $FileSize=config('config.FileSize');
        $FileSeat=config('config.FileSeat');
        $FileExt=config('config.FileExt');
        $info = $file->validate(['size'=>$FileSize,'ext'=>$FileExt])->move(PUBLIC_PATH . $FileSeat);
        if($info){
            $getSaveName=$info->getSaveName();
            $getSaveName=str_replace('\\','/',$getSaveName);
            return $getSaveName;
        }else{
            return false;
        }
    }
    //单文件上传
    protected function OneUpload2($FileName=''){
        if(empty($FileName)) return false;
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file($FileName);
        if(empty($file)){ return false;}
        // 移动到框架应用根目录/public/uploads/ 目录下
        $FileSize=config('config.FileSize');
        $FileSeat=config('config.FileSeat');
        $FileExt=config('config.MusicExt');
        $info = $file->validate(['size'=>$FileSize*100,'ext'=>$FileExt])->move(PUBLIC_PATH . $FileSeat);
        if($info){
            $getSaveName=$info->getSaveName();
            $getSaveName=str_replace('\\','/',$getSaveName);
            return $getSaveName;
        }else{
            return false;
        }
    }
    //多文件上传
    public function MoreUpload($FileName){
        if(empty($FileName)) return false;
        // 获取表单上传文件
        $files = request()->file($FileName);
        $FileSize=config('config.FileSize');
        $FileSeat=config('config.FileSeat');
        $FileExt=config('config.FileExt');
        $Back=[];
        //dump($files);
        foreach($files as $key => $file){
            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->validate(['size'=>$FileSize,'ext'=>$FileExt])->move(ROOT_PATH . 'public' . DS . $FileSeat);
            if($info){
                $getSaveName=$info->getSaveName();
                $getSaveName=str_replace('\\','/',$getSaveName);
                $Back[$key]=$getSaveName;
            }
        }
        return $Back;
    }
    protected function base64_image_content($base64_image_content,$new_file){
        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
            $type = $result[2];
            if(!file_exists($new_file)){
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($new_file, 0700);
            }
            $new_file = $new_file.time().'_'.mt_rand(10000,99999).".{$type}";
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
                return '/'.$new_file;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
    //获取会员类型信息
    protected function GetMemberTypeList($ParentID='0')
    {
        $Where=array();
        $Where['TypePID']=['in',$ParentID];
        $Where['TypeState']='1';
        return Db::name('membertype')->field('TypeID,TypeName')->where($Where)->order('TypeSort Asc,TypeID Asc')->select();
    }
    //获取会员类型信息
    protected function GetAgentTypeList($TypeID='0')
    {
        $Where=array();
        $Where['TypeID']=['not in',$TypeID];
        $Where['TypeState']='1';
        return Db::name('membertype')->field('TypeID,TypeName')->where($Where)->order('TypeSort Asc,TypeID Asc')->select();
    }
    //创建编号
    protected function CreateNumber($CouponMarkNumber,$Mark,$Length,$CurrentSeat)
    {
        $GetInt=str_replace($Mark,'',$CouponMarkNumber);
        $GetInt+=$CurrentSeat;
        $GetIntLength=strlen($GetInt);
        //dump($GetInt); 13  6 - 2 = 4 个 0
        $Str='';
        for($i=0;$i<$Length-$GetIntLength;$i++){
            $Str.='0';
        }
        $Number=$Mark.$Str.$GetInt;
        return $Number;
    }
    //获取全局分类
    protected function GetCurrentWholeType($TypeID){
        $Where=array();
        $Where['TypePID']=$TypeID;
        $Where['TypeState']=1;
        $List=db::name('wholetype')->field('TypeID,TypeName')->where($Where)->order('TypeSort Asc,TypeID Asc')->select();
        return $List;
    }
    //获取全局分类名称
    protected function GetWholeTypeName($TypeID){
        $Where=array();
        $Where['TypeID']=$TypeID;
        $Where['TypeState']=1;
        $Info=db::name('wholetype')->field('TypeName')->where($Where)->find();
        return $Info;
    }
    //获取全局分类的id
    protected  function GetWholeTypeId($Value)
    {
        $Where=array();
        $Where['TypeName']=array('like','%'.$Value.'%');
        $Info=db::name('wholetype')->where($Where)->value('TypeID');
        return $Info;
    }
    //获取省市县id
    protected  function GetCityTypeId($Value)
    {
        $Where=array();
        $Where['TypeName']=array('like','%'.$Value.'%');
        $TypeID=db::name('citytype')->where($Where)->value('TypeID');
        return $TypeID;
    }
    protected  function GetCityTypeList($PID)
    {
        $Where=array();
        $Where['TypePID']=$PID;
        $Where['TypeState']=1;
        $List=db::name('citytype')->where($Where)->order('TypeSort Asc,TypeID Asc')->select();
        return $List;
    }
    //获取局部位置的分类数据
    protected function GetSeatTypeList($TableName,$ParentID=0)
    {
        $Where=array();
        $Where['TypePID']=$ParentID;
        $Where['TypeState']='1';
        return Db::name($TableName)->field('TypeID,TypeName,TypePath,TypeNode')->where($Where)->order('TypeSort Asc,TypeID Asc')->select();
    }
    //获取联级菜单数据
    protected function GetTypeCascadeList($SelectMarkName,$TypePathData,$TableName)
    {
        $Str='';
        if(empty($TypePathData) || empty($TableName)){
            $Str.='<select name="'.$SelectMarkName.'Type[]" onchange="GetTypeList(this,\''.$TableName.'\',\''.url('ajax/GetSeatListData').'\');">
            <option value="0">1级分类</option>';
            $List=$this->GetSeatTypeList($TableName,'0');
            if(!empty($List))
            {
                foreach ($List as $key2=>$val2)
                {
                    $Str.='<option value="'.$val2['TypeID'].'_'.$val2['TypePath'].'">'.$val2['TypeName'].'</option>';
                }
            }
            $Str.='</select>';
        }else{
            $TypePathData=explode(',',$TypePathData);
            $TypePathDataArr=$TypePathData;
            $TypePathDataArr=array_filter($TypePathDataArr);
            array_unshift($TypePathDataArr,'0');
            array_pop($TypePathDataArr);
            if(empty($TypePathDataArr)) return false;
            //dump($TypePathDataArr);
            foreach ($TypePathDataArr as $key=>$val)
            {
                $Str.='<select name="'.$SelectMarkName.'Type[]" onchange="GetTypeList(this,\''.$TableName.'\',\''.url('ajax/GetSeatListData').'\');">
                <option value="0">'.($key+1).'级分类</option>';
                $List=$this->GetSeatTypeList($TableName,$val);
                if(!empty($List))
                {
                    foreach ($List as $key2=>$val2)
                    {
                        $Selected=$val2['TypeID']==$TypePathData[$key]?'selected':'';
                        $Str.='<option value="'.$val2['TypeID'].'_'.$val2['TypePath'].'" '.$Selected.'>'.$val2['TypeName'].'</option>';
                    }
                }
                $Str.='</select>';
            }
        }
        return $Str;
    }
    //获取父分分类 $State 修改时当前级别之下的 子集则不显示
    protected function ParentTypeList($TableName,$Keyword='',$State='',$CurrentID='',$PID='0',$TempArr=array(),$Seat='')
    {
        $Where=[];
        if(empty($Keyword))
        {
            $Where['TypePID']=$PID;
            if($State=='Edit')
            {
                //dump($CurrentID);
                //dump($PID);
                if($CurrentID==$PID)
                {
                    unset($TempArr[$CurrentID]);
                    //dump($TempArr);
                    return $TempArr;
                }
            }
        }else{
            $Where['TypeName']=['like','%'.$Keyword.'%'];
        }
        //->field('id,title,node,path')
        $List=Db::name($TableName)->where($Where)->order('TypeSort asc,TypeID asc')->select();
        if(empty($List))
        {
            return $TempArr;
        }else{
            if(empty($Keyword))
            {
                foreach ($List as $key=>$val)
                {
                    $val['OldTypeName']=$val['TypeName'];
                    $val['TypeName']=$Seat.$val['TypeName'];
                    $TempArr[$val['TypeID']]=$val;
                    $TempArr=$this->ParentTypeList($TableName,$Keyword,$State,$CurrentID,$val['TypeID'],$TempArr,$Seat.'　　');
                }
            }else{
                $TempArr=$List;
            }
            return $TempArr;
        }
    }
	//获取父分分类 $State 修改时当前级别之下的子集则不显示
    protected function ParentTypeListji($TableName,$UrlParam)
    {
        $Where=[];

        if(!empty($UrlParam['keyword']))
        {
			 $Where['TypeName']=['like','%'.$UrlParam['keyword'].'%'];
        }else{
			if(!empty($UrlParam['PID']))
			{
				$Where['TypePID']=intval($UrlParam['PID']);
			}else{
				$Where['TypePID']=0;
			}
		}
        $List=Db::name('wholetype')
			->where($Where)
			->order('TypeSort asc,TypeID asc')
			->paginate(50,false,['query'  => $UrlParam])
			->each(function($item, $key){
			$count=Db::name('wholetype')->where(['TypePID'=>$item['TypeID']])->count();
			$item['count']=$count;
			return $item;
			});
		return $List;
    }
    //删除图片
    protected function DelUpLoad($MainFieldID,$ID,$TableName,$Fields,$AdditionalParam=array())
    {
        if(empty($ID)) return false;
        $Where=array();
        $Where[$MainFieldID]=['in',$ID];
        if(!empty($AdditionalParam)) $Where=array_merge($Where,$AdditionalParam);
        $List=Db::name($TableName)->field($Fields)->where($Where)->select();
        if(!empty($List))
        {
            foreach ($List as $key=>$value)
            {
                if(!empty($value))
                {
                    foreach ($value as $key2=>$val2)
                    {
                        @unlink($this->UpLoadSeat.$val2);
                    }
                }
            }
        }
    }
    //删除单个旧图片
    protected function DelOneOldPic($ID,$TableName,$MainKeyID,$Fields)
    {
        if(empty($ID) || empty($TableName) || empty($MainKeyID) || empty($Fields)) return false;
        $Where=[];
        $Where[$MainKeyID]=['in',$ID];//10  20   30,40,50,60
        $List=Db::name($TableName)->where($Where)->column($Fields);//->fetchSql(true)
        if(!empty($List))
        {
            foreach ($List as $key =>$val)
            {
                if(!empty($val))
                {
                    $Path=config('config.FileSeat').'/'.$val;
                    @unlink($Path);
                }
            }
        }
    }
    //删除多个旧图片
    protected function DelMoreOldPic($ID,$TableName,$MainKeyID,$Fields,$ParamWhere=[])
    {
        if(empty($ID) || empty($TableName) || empty($MainKeyID) || empty($Fields)) return false;
        $Where=[];
        $Where[$MainKeyID]=['in',$ID];//10  20   30,40,50,60
        if(!empty($ParamWhere)){$Where=array_merge($Where,$ParamWhere);}
        //dump($Where);exit();
        $List=Db::name($TableName)->field($Fields)->where($Where)->select();//->fetchSql(true)
        if(!empty($List))
        {
            $FileSeat=config('config.FileSeat');
            foreach ($List as $key =>$val)
            {
                if(!empty($val))
                {
                    foreach ($val as $k=>$v)
                    {
                        $Path=$FileSeat.'/'.$v;
                        @unlink($Path);
                    }
                }
            }
        }
    }
	// 文件上传方法
    public function upload()
    {
        $upload = upload('upload');
        if (is_array($upload)) {
            json(1, $upload);
        } else {
            json(0, $upload);
        }
    }


	// 检查是否在黑名单
    private function checkLoginBlack()
    {
        // 读取黑名单
        $ip_black = ROOT_PATH . '/data/' . md5('login_black') . '.php';
        if (file_exists($ip_black)) {
            $data = require $ip_black;
            $user_ip = get_user_ip();
            $lock_time = $this->config('lock_time') ?: 900;
            $lock_count = $this->config('lock_count') ?: 5;
            if (isset($data[$user_ip]) && $data[$user_ip]['count'] >= $lock_count && time() - $data[$user_ip]['time'] < $lock_time) {
                return $lock_time - (time() - $data[$user_ip]['time']); // 返回剩余秒数
            }
        }
        return false;
    }

    // 添加登录黑名单
    private function setLoginBlack()
    {
        // 读取黑名单
        $ip_black = ROOT_PATH . '/data/' . md5('login_black') . '.php';
        if (file_exists($ip_black)) {
            $data = require $ip_black;
        } else {
            $data = array();
        }

        // 添加IP
        $user_ip = get_user_ip();
        $lock_time = $this->config('lock_time') ?: 900;
        $lock_count = $this->config('lock_count') ?: 5;
        if (isset($data[$user_ip]) && $data[$user_ip]['count'] < $lock_count && time() - $data[$user_ip]['time'] < $lock_time) {
            $data[$user_ip] = array(
                'time' => time(),
                'count' => $data[get_user_ip()]['count'] + 1
            );
        } else {
            $data[$user_ip] = array(
                'time' => time(),
                'count' => 1
            );
        }

        // 写入黑名单
        check_file($ip_black, true);
        return file_put_contents($ip_black, "<?php\nreturn " . var_export($data, true) . ";");
    }
}